
/* SOURCE-CODE-START */

"use strict";

var CurrentRunningApp = (function () {
  if (typeof CurrentRunningApp !== 'undefined') {
    return CurrentRunningApp;
  }

  var CurrentRunningApp = {
    fn: {},
    data: {},
    sharing: {},
    addSharing: addSharing,
    addData: addData,
    hasPrivilege: hasPrivilege,
    DATA_PRIVILEGES: '$$privileges$$',
    DATA_TENANT_ID: '$$tenantId$$',
    DATA_USER_ID: '$$userId$$',
    DATA_USER_NAME: '$$userName$$',
    DATA_USER_TYPE: '$$userType$$'
  };

  var _sharding = CurrentRunningApp.sharing;
  var _data = CurrentRunningApp.data;

  /**
   * 添加共享
   * @param {string} [namespace]
   * @param {function} callback 
   */
  function addSharing() {
    if (arguments.length >= 2) {
      var namespace = arguments[0];
      var callback = arguments[1];

      var scope = _sharding[namespace];
      if (scope == null) {
        scope = {};
        _sharding[namespace] = scope;
      }

      callback(scope);
    } else if (arguments.length >= 1) {
      var callback = arguments[0];
      callback(_sharding);
    }
  }

  /**
   * 添加数据
   * @param {string} [namespace]
   * @param {string} key 
   * @param {*} value 
   */
  function addData() {
    if (arguments.length >= 3) {
      var namespace = arguments[0];
      var key = arguments[1];
      var value = arguments[2];

      var scope = _data[namespace];
      if (scope == null) {
        scope = {};
        _data[namespace] = scope;
      }

      scope[key] = value;
    } else if (arguments.length >= 1) {
      var key = arguments[0];
      var value = arguments[1];

      _data[key] = value;
    }
  }

  /**
   * 判断是否拥有指定权限
   * @param {(string|...string)} expected 期望应当有的权限
   * @returns {boolean}
   */
  function hasPrivilege() {
    if (arguments.length <= 0) {
      return false;
    }

    var userType = _data[CurrentRunningApp.DATA_USER_TYPE];
    // 默认超级管理员拥有所有权限
    if (userType === 'SUPER_ADMIN') {
      return true;
    }

    var privileges = _data[CurrentRunningApp.DATA_PRIVILEGES];
    if (!(privileges instanceof Array)) {
      return false;
    }

    for (var index = 0; index < arguments.length; index++) {
      if (!privileges.includes[arguments[index]]) {
        return false;
      }
    }

    return true;
  };


  return CurrentRunningApp;
})();


/* SOURCE-CODE-END */

export { CurrentRunningApp };

